package com.su.dolphin.utils;

import java.text.SimpleDateFormat;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Parcelable;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;

import com.su.dolphin.DpApp;
import com.su.dolphin.R;
import com.su.dolphin.common.SpKeys;

/**
 * 常用工具类.
 */
public class SystemUtil
{
    
    private static PackageInfo sPackageInfo;
    
    public static PackageInfo getPackageInfo() {
        if (sPackageInfo == null) {
            try {
                sPackageInfo = DpApp.getContext().getPackageManager().getPackageInfo(DpApp.getContext().getPackageName(), 0);
            }
            catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return sPackageInfo;
    }
    
    /**
     * 获取版本号
     * 
     * @param context
     * @return
     */
    public static String getVersionName() {
        String versionName = null;
        if (getPackageInfo() != null) {
            versionName = sPackageInfo.versionName;
        }
        return versionName;
    }
    
    /**
     * 获取版本编号
     * 
     * @param context
     * @return
     */
    public static int getVersionCode() {
        int versionCode = 0;
        if (getPackageInfo() != null) {
            versionCode = sPackageInfo.versionCode;
        }
        return versionCode;
    }
    
    public static String getPackageName() {
        return DpApp.getContext().getPackageName();
    }
    
    /**
     * 获取渠道号
     * 
     * @return
     */
    public static String getChannelId() {
        ApplicationInfo ai;
        try {
            ai = DpApp.getContext().getPackageManager().getApplicationInfo(DpApp.getContext().getPackageName(), PackageManager.GET_META_DATA);
            Object value = ai.metaData.get("UMENG_CHANNEL");
            if (value != null) {
                return value.toString();
            }
        }
        catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1008";
    }
    
    /**
     * 判断是否存在快捷方式
     * 
     * @param mContext
     * @return
     */
    public static boolean hasShortcut(Context cx) {
        boolean result = false;
        // 获取当前应用名称
        String title = null;
        try {
            final PackageManager pm = cx.getPackageManager();
            title = pm.getApplicationLabel(pm.getApplicationInfo(cx.getPackageName(), PackageManager.GET_META_DATA)).toString();
        }
        catch (Exception e) {}
        
        final String uriStr;
        if (android.os.Build.VERSION.SDK_INT < 8) {
            uriStr = "content://com.android.launcher.settings/favorites?notify=true";
        }
        else {
            uriStr = "content://com.android.launcher2.settings/favorites?notify=true";
        }
        final Uri CONTENT_URI = Uri.parse(uriStr);
        Cursor c = null;
        try {
            c = cx.getContentResolver().query(CONTENT_URI, new String[] { "title", "iconResource" }, "title=?", new String[] { title }, null);
            if (c != null && c.getCount() > 0) {
                result = true;
            }
        }
        catch (Exception e) {}
        finally {
            if (c != null) {
                c.close();
            }
        }
        
        return result;
    }
    
    /**
     * 创建桌面快捷方式
     * 
     * @param mContext
     */
    public static void addShortcut(Context cx) {
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        
        Intent shortcutIntent = cx.getPackageManager().getLaunchIntentForPackage(cx.getPackageName());
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        // 获取当前应用名称
        String title = null;
        try {
            final PackageManager pm = cx.getPackageManager();
            title = pm.getApplicationLabel(pm.getApplicationInfo(cx.getPackageName(), PackageManager.GET_META_DATA)).toString();
        }
        catch (Exception e) {}
        // 快捷方式名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
        // 不允许重复创建（不一定有效）
        shortcut.putExtra("duplicate", false);
        // 快捷方式的图标
        Parcelable iconResource = Intent.ShortcutIconResource.fromContext(cx, R.drawable.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        
        cx.sendBroadcast(shortcut);
    }
    
    /**
     * 获取设备的IMEI
     * 
     */
    public static String getIMEI() {
        String imei = null;
        imei = DataStoreUtil.i().getString(SpKeys.KEY_IMEI, null);
        if (!TextUtils.isEmpty(imei)) {
            return imei;
        }
        else {
            imei = ((TelephonyManager) DpApp.getContext().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        }
        DataStoreUtil.i().putString(SpKeys.KEY_IMEI, imei);
        return imei;
    }
    
    /**
     * 获取设备唯一id
     * 
     * @return 唯一id 先尝试获取androidid, 然后是 IMEI 如果不能获取就生成一个UUID
     */
    public static String getDeviceId() {
        String deviceId = null;
        
        deviceId = DataStoreUtil.i().getString(SpKeys.KEY_DEVICE_ID, null);
        if (!TextUtils.isEmpty(deviceId)) {
            return deviceId;
        }
        else {
            
            deviceId = Secure.getString(DpApp.getContext().getContentResolver(), Secure.ANDROID_ID);
            if (!"9774d56d682e549c".equals(deviceId) && !TextUtils.isEmpty(deviceId)) {
                // do nothing
            }
            else {
                deviceId = getIMEI();
                if (TextUtils.isEmpty(deviceId)) {
                    deviceId = UUID.randomUUID().toString();
                }
            }
            DataStoreUtil.i().putString(SpKeys.KEY_DEVICE_ID, deviceId);
        }
        
        return deviceId;
    }
    
    /*
     * 隐藏输入法
     */
    public static void hideInputMethod(Context context, View view) {
        if (context == null || view == null)
            return;
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    
    /*
     * 显示输入法
     */
    public static void showInputMethod(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (!imm.isActive()) {
            imm.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
        }
    }
    
    /**
     * 获取屏幕的宽和高, 返回的是一个数组, int[0] 是宽度, int[1] 是高度
     * 
     * @return
     */
    public static int[] getScreenWH() {
        DisplayMetrics dm = DpApp.getContext().getResources().getDisplayMetrics();
        int[] res = new int[2];
        res[0] = dm.widthPixels;
        res[1] = dm.heightPixels;
        return res;
    }
    
    public static int getStatusBarHeight(Activity context) {
        Rect frame = new Rect();
        Window window = context.getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        LogUtil.d("statusBarHeight " + statusBarHeight);
        return statusBarHeight;
    }
    
    public static int getActionBarHeight(Activity context) {
        ActionBar actionBar = context.getActionBar();
        if (actionBar != null) {
            return actionBar.getHeight();
        }
        return 0;
    }
    
    /**
     * 
     * @title: getStateTitleBarHeight
     * @description: //状态栏标题栏的总高度,所以标题栏的高度为top2-top
     * @param context
     * @return
     * @return: int
     */
    public static int getStateTitleBarHeight(Activity context) {
        View v = context.getWindow().findViewById(Window.ID_ANDROID_CONTENT);///获得根视图
        return v.getTop();
    }
    
    public static String getBuildTime() {
        String s = "";
        try {
            ApplicationInfo ai = DpApp.getContext().getPackageManager().getApplicationInfo(getPackageName(), 0);
            ZipFile zf = new ZipFile(ai.sourceDir);
            ZipEntry ze = zf.getEntry("classes.dex");
            long time = ze.getTime();
            s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
            zf.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
}
